<template>
    <div class="dish-container">
        <!-- 搜索表单 -->
        <div class="search-form">
            <div class="form-item">
                <label>名称：</label>
                <el-input v-model="searchForm.name" placeholder="菜品名称" class="form-input" />
            </div>

            <div class="form-item">
                <label>分类：</label>
                <el-select v-model="searchForm.category" placeholder="请选择菜品分类" class="form-input">
                    <el-option label="鱼类" value="鱼类" />
                    <el-option label="汤类" value="汤类" />
                    <el-option label="中式主食" value="中式主食" />
                </el-select>
            </div>

            <div class="form-item">
                <label>状态：</label>
                <el-select v-model="searchForm.status" placeholder="请选择菜品状态" class="form-input">
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                </el-select>
            </div>

            <el-button class="search-btn" @click="handleSearch">查询</el-button>
            <el-button class="add-btn" @click="handleAddDish" color="#ffc200" :icon="CirclePlus">
                增加菜品
            </el-button>
            <el-button class="batch-delete-btn" @click="handleBatchDelete" :disabled="selectedRows.length === 0"
                color="#F56C6C" :icon="Delete">
                批量删除
            </el-button>
        </div>

        <!-- 菜品表格 -->
        <div class="table-container">
            <el-table :data="paginatedData" :fit="true" :cell-style="{ height: '80px', padding: '12px 0' }" stripe
                style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="菜品名称" />
                <el-table-column prop="imageUrl" label="图片" width="120" align="center">
                    <template #default="{ row }">
                        <img :src="row.imageUrl" alt="菜品图片" class="dish-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="categoryName" label="菜品分类" align="center" />
                <el-table-column prop="price" label="售价" width="120" align="center">
                    <template #default="{ row }">
                        <span>¥{{ row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="isAvailable" label="售卖状态" width="90" align="center">
                    <template #default="{ row }">
                        <StatusTag :status="row.isAvailable === 1 ? 'onSale' : 'unSale'" />
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="最后操作时间" width="150" align="center">
                    <template #default="{ row }">
                        <span>{{ formatDateTime(row.updateTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template #default="{ row }">
                        <el-button link size="large" type="primary" @click="openEditDrawer(row)">
                            修改
                        </el-button>
                        <el-button link size="large" type="danger" @click="handleDelete(row)">
                            删除
                        </el-button>
                        <el-button link size="large" :type="row.isAvailable === 1 ? 'warning' : 'success'"
                            @click="handleToggleStatus(row)">
                            {{ row.isAvailable === 1 ? '停售' : '启售' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <span>共 {{ totalPages }} 页</span>
            <el-pagination layout="prev, pager, next" :total="filteredDishList.length" :current-page="currentPage"
                :page-size="pageSize" @current-change="handlePageChange" :background="false" />
            <span>前往</span>
            <el-input v-model.number="goToPage" @keyup.enter="handleGoToPage" class="page-input" />
            <span>页</span>
        </div>

        <!-- 编辑抽屉
        <el-drawer v-model="drawerVisible" title="菜品信息" :direction="drawerDirection" :before-close="handleDrawerClose">
            <Edit v-if="selectedDish" :dish="selectedDish" @update:dish="handleDishUpdate"
                @close="drawerVisible = false" />
        </el-drawer> -->
    </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted } from 'vue'
import { CirclePlus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import Edit from './components/Edit.vue'
import StatusTag from './components/StatusTag.vue'
import type { DrawerProps } from 'element-plus'
import { showAddDishDrawer } from '@/utils/addDish'
import type { Dish } from '@/types/dish'
import { getStoreInfo } from '@/services/api/store'
import { getDishList } from '@/services/api/dish'
import type { PageInfo,Result } from '@/types'

// 定义口味数据类型，与Edit.vue组件中的Flavor类型对应
interface Flavor {
    dishesId: number | null
    flavorType: string
    flavorOptions: string
    isRequired: number
    maxSelections: number
    minSelections: number
}

// 定义菜品数据类型，与Edit.vue组件中的DishData类型对应
interface DishData {
    dishesId: number
    name: string
    imageUrl: string
    categoryName: string
    price: number
    originalPrice: number
    isAvailable: number
    description: string
    monthlySales: number
    rating: number
    ratingCount: number
    sortOrder: number
    storeId: number
    updateTime: string
    createTime: string
    flavors?: Flavor[]
}

onMounted(async () => {
    try {
        const storeInfo = await getStoreInfo()
        const storeId = storeInfo.data.storeId

        // 确保 storeId 是有效的
        if (storeId !== null && storeId !== undefined) {
            // 确保 currentPage 是有效数字
            const pageNum = currentPage.value || 1

            const parms = {
                storeId,
                pageNum
            }
            
            const res: Result<PageInfo<Dish>> = await getDishList(parms)
            console.log(res);
            
            dishList.value = res.data.list
            // 修复：应该使用总条目数计算总页数，而不是 pageSize
            totalPages.value = Math.ceil(res.data.total / res.data.pageSize)
            currentPage.value = res.data.pageNum
        } else {
            ElMessage.error('获取门店信息失败，无法加载菜品列表')
        }
    } catch (error) {
        console.error('获取菜品列表失败:', error)
        ElMessage.error('获取菜品列表失败')
    }
})


// 搜索表单数据
const searchForm = reactive({
    name: '',
    category: '',
    status: ''
})

// 菜品数据
const dishList = ref<Dish[]>([
])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const goToPage = ref<number | ''>(1)

// 选中行相关
const selectedRows = ref<Dish[]>([])
const handleSelectionChange = (selection: Dish[]) => {
    selectedRows.value = selection
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0] + ' ' + date.toISOString().split('T')[1].split('.')[0];
}

// 过滤后的菜品列表
const filteredDishList = computed(() => {
    return dishList.value.filter(dish => {
        return (
            (searchForm.name ? dish.name.includes(searchForm.name) : true) &&
            (searchForm.category ? dish.categoryName === searchForm.category : true) &&
            (searchForm.status ? dish.isAvailable.toString() === searchForm.status : true)
        )
    })
})

// 分页数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredDishList.value.slice(start, end)
})

// 总页数
const totalPages = ref(0)

// 抽屉相关
const drawerVisible = ref(false)
const drawerDirection = ref<DrawerProps['direction']>('rtl')
const selectedDish = ref<DishData | null>(null)

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1
}

// 处理分页变化
const handlePageChange = (page: number) => {
    currentPage.value = page
}

// 跳转到指定页
const handleGoToPage = () => {
    const page = goToPage.value
    if (typeof page === 'number' && page > 0 && page <= totalPages.value) {
        currentPage.value = page
    } else {
        ElMessage.warning('请输入有效的页码')
        // 重置为当前页
        goToPage.value = currentPage.value
    }
}

// 打开编辑抽屉
const openEditDrawer = (dish: Dish) => {
    selectedDish.value = {
        ...dish,
    } as DishData
    drawerVisible.value = true
}

// 处理菜品更新
// 修改 handleDishUpdate 方法，做类型适配
const handleDishUpdate = (updatedDish: DishData) => {
    const index = dishList.value.findIndex(dish => dish.dishesId === updatedDish.dishesId)
    if (index !== -1) {
        // 兼容 flavors 类型差异
        dishList.value[index] = {
            ...updatedDish,
            flavors: updatedDish.flavors?.map((f: Flavor) => ({
                name: f.flavorType,
                value: f.flavorOptions
            })) ?? []
        } as Dish
    }
    drawerVisible.value = false
    ElMessage.success('菜品信息更新成功')
}

// 处理抽屉关闭
const handleDrawerClose = (done: () => void) => {
    drawerVisible.value = false
    done()
}

// 新增菜品
const handleAddDish = () => {
    showAddDishDrawer(
        // 添加菜品成功回调
        (dishData) => {
            // 处理新增菜品逻辑
            console.log('新增菜品数据:', dishData)

            // 示例：添加到菜品列表
            dishList.value.push({
                ...dishData,
                dishesId: Date.now(), // 实际应由后端生成
                updateTime: new Date().toISOString(),
                createTime: new Date().toISOString()
            })

            ElMessage.success('菜品添加成功')
        },
        // 抽屉关闭回调（可选）
        () => {
            console.log('添加菜品抽屉已关闭')
        }
    )
}

// 删除菜品
const handleDelete = (dish: Dish) => {
    ElMessageBox.confirm(
        `确定要删除菜品"${dish.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        dishList.value = dishList.value.filter(item => item.dishesId !== dish.dishesId)
        selectedRows.value = selectedRows.value.filter(item => item.dishesId !== dish.dishesId)
        ElMessage.success('删除成功')
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) return

    ElMessageBox.confirm(
        `确定要删除选中的${selectedRows.value.length}个菜品吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const selectedIds = selectedRows.value.map(item => item.dishesId)
        dishList.value = dishList.value.filter(dish => !selectedIds.includes(dish.dishesId))
        selectedRows.value = []
        ElMessage.success('删除成功')
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}

// 切换菜品状态
const handleToggleStatus = (dish: Dish) => {
    const actionText = dish.isAvailable === 1 ? '停售' : '启售'

    ElMessageBox.confirm(
        `确定要${actionText}菜品"${dish.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const newStatus = dish.isAvailable === 1 ? 0 : 1
        dish.isAvailable = newStatus

        const index = dishList.value.findIndex(item => item.dishesId === dish.dishesId)
        if (index !== -1) {
            dishList.value[index].isAvailable = newStatus
        }

        ElMessage.success(`${actionText}成功`)
    }).catch(() => {
        ElMessage.info(`已取消${actionText}`)
    })
}
</script>

<style lang="scss" scoped>
.dish-container {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}

.search-form {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
    margin-bottom: 20px;

    .form-item {
        display: flex;
        align-items: center;
        gap: 5px;

        label {
            color: #663300;
            font-weight: 500;
            white-space: nowrap;
        }

        .form-input {
            width: 180px;
            height: 40px;
        }

        :deep(.el-select__wrapper) {
            height: 40px !important;
        }

        .el-select {
            --el-color-primary: #ffc200;
        }
    }

    .search-btn {
        height: 40px;
        background-color: #333;
        color: white;
        border: none;

        &:hover {
            background-color: rgba(51, 51, 51, 0.8);
        }
    }

    .add-btn,
    .batch-delete-btn {
        height: 40px;
        border: none;
        color: white;

        &:hover {
            opacity: 0.8;
        }
    }

    .add-btn {
        margin-left: auto;
    }

    .batch-delete-btn:disabled {
        background-color: #fab6b6 !important;
        color: #ffffff !important;
        opacity: 0.6;
    }
}

.table-container {
    margin-bottom: 20px;

    .dish-image {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 4px;
    }
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;

    .page-input {
        width: 50px;
    }

    span {
        font-size: 14px;
    }
}
</style>